package Salutation;
use Utils;

sub new
{
    my $class  = shift;
    my $self   = {};

    $self->{title}      = "";
    $self->{salution}   = "";
    $self->{realm_id}   = "";

    bless $self, 'Salutation';
    return $self;
}

sub newFromDB
{
    my ($class, $salutation_id)  = @_;
    my $self    = {};

    my $stmt    = "SELECT title, salutation, realm_id FROM salutations WHERE id = " . $salutation_id;

    my $kit_db  = new KIT_DB();
    my $hashref = $kit_db->GetSingleRow($stmt) || die $!;

    $self->{salutation_id}  = $salutation_id;
    $self->{title}          = $hashref->{title};
    $self->{salutation}     = $hashref->{salutation};
    $self->{realm_id}       = $hashref->{realm_id};

    bless $self, 'Salutation';
    return $self;
}

sub insert
{
    my $self    = shift;

    my $utils   = new Utils();

    my $salutation  = $utils->sanitizeApostrophe($self->{salutation});
    my $title       = $utils->sanitizeApostrophe($self->{title});

    my $kit_db  = new KIT_DB();
    my $stmt    = "INSERT INTO salutations (title, salutation, realm_id) VALUES ('$title', '$salutation', $self->{realm_id})";
    return $kit_db->Insert($stmt);
}

sub update
{
    my $self    = shift;

    my $sal_id      = $self->{salutation_id};
    my $title       = $self->{title};
    my $salutation  = $self->{salutation};

    my $stmt    = "UPDATE salutations SET title = '$title', salutation = '$salutation' WHERE id = $sal_id AND realm_id = $self->{realm_id}";
#     print $stmt; exit;
    my $kit_db  = new KIT_DB();

    return $kit_db->Update($stmt);
}

sub get_all_salutations
{
    my ($self, $active) = @_;
    my $stmt    = "SELECT id, title, salutation FROM salutations WHERE realm_id = " . $self->{realm_id};

    my $kit_db	= new KIT_DB();

    my @salutations = ();
    my @rows        = $kit_db->GetMultipleRows($stmt);

    foreach (@rows)
    {
        my %salutation  = (
            salutation_id   => $_->[0],
            title           => $_->[1],
            salutation      => $_->[2],
        );
        push @salutations, \%salutation;
    }
    return @salutations;
}

# sub get_greeting_by_recipient
# {
#     my $self    = shift;
#     my $rcpt_id = shift;
# 
#     my $recipient   = newFromDBById Recipient($rcpt_id);
# 
#     if ( ($recipient->{'salutation_id'} > 0) && ($recipient->{'salutation_include'} > 0) )
#     {
# #         use Salutation;
#         $salutation  = newFromDB ($recipient->{salutation_id});
#         $greeting    = $salutation->{'salutation'} . " ";
#     }
# 
#     $greeting    .= trim($recipient->{'f_name'}) . " "
#         if ($recipient->{'f_name'} && $recipient->{'f_name_include'} > 0);
# 
#     $greeting    .= trim($recipient->{'l_name'})
#         if ($recipient->{'l_name'} && $recipient->{'l_name_include'} > 0);
# 
#     $recipient->{greeting}   = trim($greeting);
#     return $greeting;
# }

1;